use std::{
    sync::{mpsc, Arc, Mutex},
    thread
};
type Job = Box<dyn FnOnce() + Send + 'static>;

struct Worker {
    id: usize,
    thread: Option<thread::JoinHandle<()>>    
}

impl Worker {
    //所有的worker其实是共享一个receiver，所以需要Arc+Mutex.以便满足mpsc的要求
    //这种设计也只能满足于比较简单的场景，如果要支持复杂的场景，就需要用到更复杂的设计
    fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
        //创建一个不断循环的线程，不断接收消息并执行任务
        //者是一个死循环，如何会退出了？
        //spawn返回一个JoinHandle，可以用来等待线程结束
        let thread = thread::spawn(move || loop {
            let message = receiver.lock().unwrap().recv();
            match message {
                Ok(job) => {
                    println!("Worker {id} got a job; executing.");
                    job();
                }
                Err(_) => {
                    println!("Worker {id} disconnected; shutting down.");
                    break;
                }
            }
        });

        Worker {
            id,
            thread: Some(thread),
        }
    }
}


pub struct ThreadPool {
    workers: Vec<Worker>,
    sender: Option<Arc<mpsc::Sender<Job>>>,
}

impl ThreadPool {
    pub fn new(size: usize) -> ThreadPool {
        assert!(size > 0);
        let (sender, receiver) = mpsc::channel();
        let receiver = Arc::new(Mutex::new(receiver));
        let mut workers = Vec::with_capacity(size);
        for id in 0..size {
            workers.push(Worker::new(id, Arc::clone(&receiver)));
        }

        ThreadPool {
            workers,
            sender: Some(Arc::new(sender)),
        }
    }

    pub fn get_sender(&self) -> Option<Arc<mpsc::Sender<Job>>> {
        // as_ref() 返回一个Option的引用，形如 Opotion<&T>
        // Option的map接受一个匿名函数/闭包,对其中的T执行闭包，并返回一个新的Option
        self.sender.as_ref().map(Arc::clone)
    }

    pub fn execute<F>(&self, f: F)
    where
        F: FnOnce() + Send + 'static,
    {
        let job = Box::new(f);
        self.sender.as_ref().unwrap().send(job).unwrap();
    }
}

impl Drop for ThreadPool {
    fn drop(&mut self) {
        //删除sender,会导致receiver收到一个错误，导致所有worker退出循环
        //take()会返回Option中的T，并把Option设置为None
        drop(self.sender.take());
        for worker in &mut self.workers {
            println!("Shutting down worker {}", worker.id);
            if let Some(thread) = worker.thread.take() {
                thread.join().unwrap();
            }
        }
    }
}


